package com.seanzx.dp.serializer.impl;

import com.seanzx.dp.common.Persist;
import com.seanzx.dp.entity.Column;
import com.seanzx.dp.serializer.ISerializer;

import java.io.FilterInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * VARCHAR: |length|content| first n bytes record the length of content.
 *          length of the column configuration smaller than 256, use 1 byte.
 *          else if smaller than 65536, use 2 bytes.
 *          ...
 *          if the content is null, the length is 1 while the content is 000.
 */
public class VarcharSerializer implements ISerializer {
    @Override
    public String deserialize(Column column, FilterInputStream inputStream) throws IOException {
        byte[] lengthBytes = new byte[column.getLength() / 256 + 1];
        inputStream.read(lengthBytes);
        int sum = 0;
        for (byte lengthByte : lengthBytes) {
            sum += lengthByte & 0xFF;
        }
        byte[] contentBytes = new byte[sum];
        inputStream.read(contentBytes);
        if (contentBytes.length == 1 && contentBytes[0] == '\000') {
            return null;
        }
        return new String(contentBytes, StandardCharsets.UTF_8);
    }

    @Override
    public byte[] serialize(Column column, String value) {
        return Persist.getVarcharBytes(column.getLength(), value);
    }

    public static void main(String[] args) {
        byte[] bytes = Persist.getVarcharBytes(255, "Stairway To Heaven, There's a lady who's sure all that glitters is gold");
//        byte[] bytes = Persist.getVarcharBytes(255, null);

        byte[] lengthBytes = new byte[255 / 256 + 1];
        System.arraycopy(bytes, 0, lengthBytes, 0, lengthBytes.length);
        int sum = 0;
        for (byte lengthByte : lengthBytes) {
            sum += lengthByte & 0xFF;
        }
        byte[] contentBytes = new byte[sum];
        for (int i = lengthBytes.length; i < contentBytes.length + lengthBytes.length; i++) {
            contentBytes[i - lengthBytes.length] = bytes[i];
        }
        if (contentBytes.length == 1 && contentBytes[0] == '\000') {
            System.out.println("null");
        }
        System.out.println(new String(contentBytes, StandardCharsets.UTF_8));
    }
}
